
function Yupoo() {}
Yupoo.prototype = {
	API_KEY 		: '2e7f6b3f4438c334e110887a0da87aec',
	SHARED_SECRET 	: 'esthlxk8zdtnsbsz',
	URL_REST		: 'http://www.yupoo.com/api/rest/',
	URL_AUTH		: 'http://www.yupoo.com/services/auth/',
	URL_UPLOAD		: 'http://www.yupoo.com/api/upload/',
	
	frob : '',
	token : '',
	
	getFrobAndAuth : function() {
		var _this = this;
		this.call({method: 'yupoo.auth.getFrob'}, this.URL_REST, function(xRequest){
			var frobReturn = xRequest.responseXML.getElementsByTagName("frob");
			_this.frob = frobReturn[0].firstChild.nodeValue;
			var authURL = _this.getSortedQueryString({frob: _this.frob, perms: 'write'}, _this.URL_AUTH);
			//opening a new focused tab.
	        const kWindowMediatorContractID = "@mozilla.org/appshell/window-mediator;1";
	        const kWindowMediatorIID = Components.interfaces.nsIWindowMediator;
	        const kWindowMediator = Components.classes[kWindowMediatorContractID].getService(kWindowMediatorIID);
	        var browserWindow = kWindowMediator.getMostRecentWindow("navigator:browser");
	        var browser = browserWindow.getBrowser();
	        var tab = browser.addTab(authURL);
	        browser.selectedTab = tab;
	        nsPreferences.setUnicharPref("cn.xpies.siteshot.com.yupoo.frob", _this.frob);
			return _this.frob;
		});
	},
	getToken : function() {
		try {
			this.token = nsPreferences.copyUnicharPref("cn.xpies.siteshot.com.yupoo.token","");
			this.frob = nsPreferences.copyUnicharPref("cn.xpies.siteshot.com.yupoo.frob","");
		} catch(e) {
			alert(e)
		}
		var _this = this;
		if (!this.token) {
			this.call({method: 'yupoo.auth.getToken', frob: this.frob}, this.URL_REST, function(xRequest){
				var tokenReturn = xRequest.responseXML.getElementsByTagName("token");
				_this.token = tokenReturn[0].firstChild.nodeValue;
				nsPreferences.setUnicharPref("cn.xpies.siteshot.com.yupoo.token", _this.token);
			}, function(xRequest) {
				_this.getFrobAndAuth();
			});
		}
	},
	
	checkToken : function() {
		var _this = this;
		this.call({method: 'yupoo.auth.checkToken'}, this.URL_REST, function(xRequest) {
			var tokenReturn = xRequest.responseXML.getElementsByTagName("token");
			_this.token = tokenReturn[0].firstChild.nodeValue;
			nsPreferences.setUnicharPref("cn.xpies.siteshot.com.yupoo.token", _this.token);
		}, function() {
			_this.getFrobAndAuth();
		});
	},
	
	getSortedQueryString : function(params,url) {
		params.api_key = this.API_KEY;
		var paramNames = new Array();
		for(var name in params) {
			paramNames.push(name);
		}
		var sig = '';
		var query = (url?url:this.URL_REST)+'?';
		for(var i in paramNames.sort()) {
			var name = paramNames[i];
			sig += name + params[name];
			query += name + '=' + params[name]+'&';
		}
		
		query += 'api_sig='+MD5(this.SHARED_SECRET + toutf8(sig));
		return query;
	},
	
	// call api methods
	call : function(params, url, onSuccess, onFailure) {
		if(params.auth_token == 'default')
			params.auth_token = this.token;

		// send call by XMLHttp
		var xRequest = new XMLHttpRequest();
		xRequest.open("GET",this.getSortedQueryString(params, url));
		
		// callback
		xRequest.onreadystatechange = function() {
			if(xRequest.readyState != 4) return false;
			if(xRequest.status == 200) {
				var stat = xRequest.responseXML.firstChild.getAttribute('stat');
				if(stat == 'ok') {
					if(onSuccess) onSuccess(xRequest);
				}else{
					var e = xRequest.responseXML.getElementsByTagName('err').item(0);
					var ecode = e.getAttribute('code');
					var emsg = e.getAttribute('msg');
					dump(params.method+' failed: '+ecode+' '+emsg+'\n');
					if(onFailure) onFailure(xRequest,stat,ecode,emsg);
				}
			}else{
				if(onFailure) onFailure(xRequest);
			}
			return true;
		}
		xRequest.send(null);
		return true;
	},
	
	upload : function(file, description) {
			this.getToken();
			var storageStream = Components.classes["@mozilla.org/storagestream;1"].createInstance(Components.interfaces.nsIStorageStream);
			storageStream.init(1024,10000000,null);
			var outputStream = storageStream.getOutputStream(0);
			var binOutputStream = Components.classes["@mozilla.org/binaryoutputstream;1"].createInstance(Components.interfaces.nsIBinaryOutputStream);
	   		binOutputStream.setOutputStream(outputStream);
	   		
	   		/* create POST body */
	   		var boundarytoken = 'siteshot';
	   		var boundary = '--'+boundarytoken;
	   		var body = '';
				//alert(this.token + "\n" + this.api_key);
	   		var params = { api_key: this.API_KEY, auth_token: this.token,tags: 'siteshot', is_public: '1', is_friend: '0', is_family: '0' };
	   		for(var name in description) params[name] = description[name];
	   		var paramNames = new Array();
	   		for(var name in params) paramNames.push(name);
	   		var sig = '';
			for(var i in paramNames.sort()) {
				var name = paramNames[i];
				sig += name+params[name];
				body += boundary+'\r\nContent-Disposition: form-data; name="'+name+'"\r\n\r\n'+ toutf8(params[name])+'\r\n';
			}
	   		body += boundary+'\r\nContent-Disposition: form-data; name="api_sig"\r\n\r\n'+MD5(toutf8(this.SHARED_SECRET + sig))+'\r\n';
	   		body += boundary+'\r\nContent-Disposition: form-data; name="photo"; filename="'+description.title+'"\r\nContent-Type: image/jpeg\r\nContent-Transfer-Encoding: binary\r\n\r\n';
	   		binOutputStream.writeBytes(body,body.length);
	   		var bisbytes = file.available();
	   		binOutputStream.writeBytes(file.readBytes(bisbytes),bisbytes);
	   		binOutputStream.writeBytes('\r\n'+boundary+'--\r\n',6+boundary.length); 
	   		file.close(); 
	//   		st.close();
	   		binOutputStream.close(); 
	   		outputStream.close();
	   		
	   		var xRequest = new XMLHttpRequest();
	   		xRequest.open("POST", this.URL_UPLOAD);
	   		xRequest.setRequestHeader('Content-Type', 'multipart/form-data; boundary="'+boundarytoken+'"');
	   		xRequest.setRequestHeader('Connection','close');
	   		xRequest.setRequestHeader('Content-Length',body.length);
	   		xRequest.onreadystatechange=function() {
	    		if(xRequest.readyState!=4) return false;
				if(xRequest.status==200) {
	 				var stat = xRequest.responseXML.firstChild.getAttribute('stat');
	 				if(stat=='ok') {
	 					showMessage(Utils.getLocaleString("siteshot.uploaded"));
	 					setTimeout('hideMessage()',5000);
	 					clearTimeout();
//	  					var pid = xp_str('/rsp/photos',x.responseXML);
	  					if(on_success) 
	  						on_success(xRequest,pid);
 					}else{
		  				var e = xRequest.responseXML.getElementsByTagName('err').item(0);
		  				var ecode = e.getAttribute('code');
		  				var emsg = e.getAttribute('msg');
		  				dump('upload failed: '+ecode+' '+emsg+'\n');
//			  				if(on_failure) 
//			  					on_failure(x,stat,ecode,emsg);
	 				}
				}else{
	 				if(on_failure) on_failure(xRequest);
				}
				return true;
	   		};
	   		try{
   				showMessage(Utils.getLocaleString('siteshot.uploading'));
   				xRequest.send(storageStream.newInputStream(0));
	   		}catch(e){
	   		}
 	}
	
};
